<?php

namespace addons\yunfood\model;

use addons\yunfood\library\Logic;
use addons\yunfood\library\ModelTrait;
use think\Exception;
use think\Model;

/**
 * 通知声音
 */
class NoticeVoice extends Model
{
    use ModelTrait;

    // 表名,不含前缀
    protected $name = 'yunfood_notice_voice';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    protected $resultSetType = 'collection';

    // 类型
    const TYPE_BAIDU = 'baidu';

    public static function getTypeList()
    {
        return [self::TYPE_BAIDU => __('百度语音合成')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $optionList = self::getTypeList();

        return $optionList[$data['type']] ?? $data['type'];
    }

    /**
     * 获取本地路径
     */
    public function getLocalSrcAttr($value, $data)
    {
        return $data['src'];
    }

    /**
     * 获取百度语音
     *
     * @param $content
     * @param false $update
     * @return NoticeVoice
     * @throws Exception
     */
    public static function createBaiduVoice($content, $update = false)
    {
        $type = static::TYPE_BAIDU;
        $hash = sha1($content);
        $noticeVoice = self::get(['type' => $type, 'hash' => $hash]);
        if (! $noticeVoice || $update) {
            // 保存mp3到本地
            $fileDir = '/voice/' . date('Ym');
            $filePath = ROOT_PATH . 'public/uploads/' . $fileDir;
            $filename = uniqid('', true) . '.mp3';
            if (! is_dir($filePath)) {
                @mkdir($filePath, 0777, true);
            }
            if (! is_really_writable($filePath)) {
                throw new Exception('保存音频MP3到本地时没有写入权限');
            }
            $voiceCont = Logic::baiduText2Audio($content);
            if (! $voiceCont) {
                throw new Exception('通过百度语音合成失败');
            }
            file_put_contents($filePath . '/' . $filename, $voiceCont);

            // 保存声音到数据库
            if ($noticeVoice == null) {
                $noticeVoice = new self();
                $noticeVoice['type'] = $type;
                $noticeVoice->hash = $hash;
                $noticeVoice['data'] = $content;
            }
            $noticeVoice->src = '/uploads' . $fileDir . '/' . $filename;
            $noticeVoice->save();
        }

        return $noticeVoice;
    }
}
